/*
 * Copyright 2011 CraneLeeon authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var page_UserMgt;
var loadcountflag=0;
var Page_Home = function(){
    var currentPage;
    var $tabs;
    var clickednavitem;
    this.init = function(){
        $('#NavBar').accordion({
//            collapsible: true,
            fillSpace: true,
//            event: "mouseover",
            autoHeight:true
        });
        $('#NavBar .NavItem').each(function(){
            var _t = $(this);
            _t.hover(function(){_t.addClass('NavItemHover')}, function(){_t.removeClass('NavItemHover')});
            _t.click(function(){
                if(!_t.attr('tab_id')){
                    clickednavitem = _t.attr('id');
                    openTabPage(_t.attr('url'), _t.text());
                }else{
                    $tabs.tabs('abort');
                    $tabs.tabs('select' , "#"+_t.attr('tab_id'));
                }
            });
        });
        $tabs = $('#TabContainer').tabs({
            ajaxOptions: {
                async: false,
                cache: false,
                error: function(xhr, status, index, anchor) {
                                $(anchor.hash).html("Couldn't load this tab now. Please try again later.");
                        }
            },
            collapsible: false,
//            fx: {opacity: 'toggle', duration:'fast'},
            cache: true,
            idPrefix: 'tab_',
            tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a><div class="BT_TabClose"></li>',
//            panelTemplate:'<div class="TabContant"></div>',
            add: function(event, ui){
                var tab_id = ui.panel.id;
                $('#NavBar .NavItem[id='+clickednavitem+']').attr('tab_id', tab_id);
                $(ui.tab).parent().children('div.BT_TabClose').click(function(){
                    var navitem = $('#NavBar div div.NavItem[tab_id='+tab_id+']');
                    if(navitem) {
                        navitem.removeAttr('tab_id');
                        try{
                            try{eval(navitem.attr('id')+'.clearResource()');}catch(ex){}
                            try{eval(navitem.attr('id') = null);}catch(ex){}//release function
                        }catch(ex){}
                    }
                    $tabs.tabs('abort');
                    $tabs.tabs('select','#'+tab_id);
                    $tabs.tabs('remove',$tabs.tabs('option', 'selected'));
                });
                $tabs.tabs('select', '#' + tab_id);
            },
            select: function(e, ui) {
                currentPage = ui.panel.id;
                var navitem = $('#NavBar div.NavBar_content div.NavItem[tab_id='+currentPage+']');
                try{
                    setCurrentPageDataSync(null,  eval(navitem.attr('id')).pageDataSync);
                }catch(ex){
                    removeCurrentPageDataSync();
                }
            }
            ,load: function(event, ui) {
                var tab_id = ui.panel.id;
                var navitem = $('#NavBar div div.NavItem[tab_id='+tab_id+']');
                if(navitem) {
                    var cname = 'P'+navitem.attr('id').substr(1);
                    try{eval(navitem.attr('id')+' = new '+cname+'()');}catch(ex){}
                    try{eval(navitem.attr('id')+'.init()');}catch(ex){}
                }
            }

        });
        $("#LoadingIndicator").bind("ajaxSend", function(){
            loadcountflag++;
            $(this).show();
        }).bind("ajaxComplete", function(){
            if(loadcountflag>0) loadcountflag--;
            if(loadcountflag==0) $(this).hide();
        }).hide();
//            synchronizeNotifications();
    }

    function openTabPage( _url, _label){
        $tabs.tabs('add' ,_url, _label);
    }

    

}


//Data Synchronize functions
var sync_timeout_id = null;
var sync_requester = null;

var SYNC_CALLBACK_STACK = {
    sys_notification:{
        url:'Service.action?act='+ACT_NOTIFICATIONS,
        callback:function(resTxt){
//            dlg_Message(resTxt["rows"][0].url);
        },
        period:60000
    },
    currentPageDataSync:{
        url:null,
        callback:null,
        period:5000
    }
}

var SYNC_CALLBACK_STACK_ARRAY = [
    SYNC_CALLBACK_STACK.sys_notification,
    SYNC_CALLBACK_STACK.currentPageDataSync
]

function setCurrentPageDataSync(syncUrl, syncCallBackFunc){
    if(sync_timeout_id) window.clearTimeout(sync_timeout_id);
    if(sync_requester) sync_requester.abort();
    SYNC_CALLBACK_STACK.currentPageDataSync.url = syncUrl;
    SYNC_CALLBACK_STACK.currentPageDataSync.callback = syncCallBackFunc;
    synchronizeDataOnServer();
}

function removeCurrentPageDataSync(){
    if(sync_timeout_id) window.clearTimeout(sync_timeout_id);
    if(sync_requester) sync_requester.abort();
    SYNC_CALLBACK_STACK.currentPageDataSync.url = null;
    SYNC_CALLBACK_STACK.currentPageDataSync.callback = null;
}

function synchronizeNotifications(){
    if(SYNC_CALLBACK_STACK.sys_notification) {
        if(SYNC_CALLBACK_STACK.sys_notification.url){
            $.ajax({
                type: 'POST',
                url: SYNC_CALLBACK_STACK.sys_notification.url,
                success: function(resTxt){
                    if(SYNC_CALLBACK_STACK.sys_notification.callback){
                        SYNC_CALLBACK_STACK.sys_notification.callback(resTxt);
                    }
                window.setTimeout(function(){
                    synchronizeNotifications();
                },SYNC_CALLBACK_STACK.sys_notification.period);
                },dataType: 'json'
            });
        }
    }
}

function synchronizeDataOnServer(){
    if(SYNC_CALLBACK_STACK.currentPageDataSync) {
        sync_timeout_id = window.setTimeout(function(){
            if(SYNC_CALLBACK_STACK.currentPageDataSync.url){
                $.ajax({
                    type: 'GET',
                    url: SYNC_CALLBACK_STACK.currentPageDataSync.url,
                    success: function(resTxt){
                        if(SYNC_CALLBACK_STACK.currentPageDataSync.callback){
                            SYNC_CALLBACK_STACK.currentPageDataSync.callback(resTxt);
                        }
                        synchronizeDataOnServer()
                    },dataType: 'json'
                });
            }else{
                if(SYNC_CALLBACK_STACK.currentPageDataSync.callback){
                    SYNC_CALLBACK_STACK.currentPageDataSync.callback(null);
                }
                synchronizeDataOnServer()
            }
        },SYNC_CALLBACK_STACK.currentPageDataSync.period);
    }
    
}








